<template>
  <el-dialog title="批量配置签到时间" :close-on-click-modal="false" :visible.sync="visible" class="cu-dialog cu-dialog_center" lock-scroll width="900px">
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" size="small" label-width="120px" label-position="right">
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="师训项目" prop="trainId">
            <el-select v-model="dataForm.trainId" placeholder="请选择师训项目" filterable clearable :style="{ width: '100%' }" @change="onTrainChange">
              <el-option v-for="item in trainOptions" :key="item.id" :label="item.title" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="日期范围" prop="dateRange">
            <el-date-picker v-model="dataForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :picker-options="datePickerOptions" :style="{ width: '100%' }" />
            <div v-if="selectedTrainDateRange" class="date-range-hint">
              <small style="color: #909399;">师训日期范围: {{ selectedTrainDateRange }}</small>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="时段配置">
            <div class="period-config-container">
              <div v-for="(period, index) in dataForm.periodConfigs" :key="index" class="period-config-item">
                <div class="period-header">
                  <el-checkbox v-model="period.enabled" @change="onPeriodEnabledChange(period)">
                    {{ getPeriodLabel(period.periodName) }}
                  </el-checkbox>
                  <el-button v-if="dataForm.periodConfigs.length > 1" type="text" size="mini" icon="el-icon-delete" class="delete-btn" @click="removePeriodConfig(index)">
                    删除
                  </el-button>
                </div>
                <div v-if="period.enabled" class="period-content">
                  <el-row :gutter="10">
                    <el-col :span="8">
                      <el-form-item label="开始" :prop="`periodConfigs.${index}.startTime`" label-width="60px">
                        <el-time-picker v-model="period.startTime" placeholder="开始时间" format="HH:mm" value-format="HH:mm" size="mini" :style="{ width: '100%' }" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="结束" :prop="`periodConfigs.${index}.endTime`" label-width="60px">
                        <el-time-picker v-model="period.endTime" placeholder="结束时间" format="HH:mm" value-format="HH:mm" size="mini" :style="{ width: '100%' }" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="迟到阈值" :prop="`periodConfigs.${index}.lateMinutes`" label-width="80px">
                        <el-input-number v-model="period.lateMinutes" placeholder="分钟" :min="0" :max="60" size="mini" :style="{ width: '100%' }" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="备注" label-width="60px">
                        <el-input v-model="period.remark" placeholder="请输入备注" size="mini" maxlength="200" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </div>
              <el-button type="dashed" size="mini" icon="el-icon-plus" @click="addPeriodConfig">
                添加时段
              </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { batchConfigTrainSignTime } from '@/api/campus/trainSignTimeConfig'
import { getTrainSelector } from '@/api/campus/train'

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        trainId: '',
        dateRange: [],
        periodConfigs: [
          {
            periodName: 'AM',
            startTime: '08:00',
            endTime: '12:00',
            lateMinutes: 15,
            enabled: true,
            remark: ''
          },
          {
            periodName: 'PM',
            startTime: '14:00',
            endTime: '18:00',
            lateMinutes: 15,
            enabled: true,
            remark: ''
          },
          {
            periodName: 'EVE',
            startTime: '19:00',
            endTime: '22:00',
            lateMinutes: 15,
            enabled: false,
            remark: ''
          }
        ]
      },
      dataRule: {
        trainId: [{ required: true, message: '请选择师训项目', trigger: 'change' }],
        dateRange: [{ required: true, message: '请选择日期范围', trigger: 'change' }]
      },
      trainOptions: []
    }
  },
  computed: {
    // 当前选中师训的日期范围
    selectedTrain() {
      return this.trainOptions.find(train => train.id === this.dataForm.trainId)
    },
    // 日期选择器限制选项
    datePickerOptions() {
      if (!this.selectedTrain) {
        return {}
      }

      try {
        const startDate = this.selectedTrain.startDate
        const endDate = this.selectedTrain.endDate

        if (!startDate || !endDate) {
          console.warn('师训项目缺少日期信息:', this.selectedTrain)
          return {}
        }

        const trainStartDate = new Date(startDate)
        const trainEndDate = new Date(endDate)

        if (isNaN(trainStartDate.getTime()) || isNaN(trainEndDate.getTime())) {
          console.warn('师训项目日期格式无效:', { startDate, endDate })
          return {}
        }

        return {
          disabledDate: time => {
            const currentDate = new Date(time.getFullYear(), time.getMonth(), time.getDate())
            const startCompare = new Date(trainStartDate.getFullYear(), trainStartDate.getMonth(), trainStartDate.getDate())
            const endCompare = new Date(trainEndDate.getFullYear(), trainEndDate.getMonth(), trainEndDate.getDate())

            return currentDate < startCompare || currentDate > endCompare
          }
        }
      } catch (error) {
        console.error('处理师训日期限制时出错:', error)
        return {}
      }
    },
    // 显示师训日期范围的文本
    selectedTrainDateRange() {
      if (!this.selectedTrain) {
        return ''
      }

      try {
        const startDate = this.selectedTrain.startDate
        const endDate = this.selectedTrain.endDate

        if (!startDate || !endDate) {
          return '日期信息不完整'
        }

        const start = new Date(startDate)
        const end = new Date(endDate)

        if (isNaN(start.getTime()) || isNaN(end.getTime())) {
          return '日期格式无效'
        }

        const formatDate = date => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }

        return `${formatDate(start)} 至 ${formatDate(end)}`
      } catch (error) {
        console.error('格式化师训日期范围时出错:', error)
        return '日期处理错误'
      }
    }
  },
  methods: {
    init(defaultTrainId) {
      this.visible = true
      this.getTrainOptions()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (defaultTrainId) {
          // 设置默认师训项目
          this.dataForm.trainId = defaultTrainId
        }
      })
    },
    async getTrainOptions() {
      try {
        const res = await getTrainSelector()
        if (res.code === 200) {
          this.trainOptions = res.data || []
        }
      } catch (error) {
        console.error('获取师训列表失败:', error)
      }
    },
    // 师训项目改变时的处理
    onTrainChange() {
      // 清空之前的日期范围
      this.dataForm.dateRange = []

      // 如果选中了师训项目，自动设置为师训的日期范围
      if (this.selectedTrain && this.selectedTrain.startDate && this.selectedTrain.endDate) {
        try {
          const startDate = new Date(this.selectedTrain.startDate)
          const endDate = new Date(this.selectedTrain.endDate)

          if (!isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
            const formatDate = date => {
              const year = date.getFullYear()
              const month = String(date.getMonth() + 1).padStart(2, '0')
              const day = String(date.getDate()).padStart(2, '0')
              return `${year}-${month}-${day}`
            }

            this.dataForm.dateRange = [formatDate(startDate), formatDate(endDate)]
          }
        } catch (error) {
          console.error('设置默认日期范围时出错:', error)
        }
      }
    },
    getPeriodLabel(period) {
      const labelMap = {
        AM: '上午',
        PM: '下午',
        EVE: '晚上'
      }
      return labelMap[period] || period
    },
    onPeriodEnabledChange(period) {
      // 当启用状态改变时的处理逻辑
    },
    addPeriodConfig() {
      this.dataForm.periodConfigs.push({
        periodName: 'AM',
        startTime: '08:00',
        endTime: '12:00',
        lateMinutes: 15,
        enabled: true,
        remark: ''
      })
    },
    removePeriodConfig(index) {
      this.dataForm.periodConfigs.splice(index, 1)
    },
    validatePeriodConfigs() {
      const enabledConfigs = this.dataForm.periodConfigs.filter(p => p.enabled)
      if (enabledConfigs.length === 0) {
        this.$message.error('至少需要启用一个时段配置')
        return false
      }

      for (let i = 0; i < enabledConfigs.length; i++) {
        const config = enabledConfigs[i]
        if (!config.periodName || !config.startTime || !config.endTime) {
          this.$message.error('请完善时段配置信息')
          return false
        }

        const startTime = new Date(`2000-01-01 ${config.startTime}`)
        const endTime = new Date(`2000-01-01 ${config.endTime}`)
        if (endTime <= startTime) {
          this.$message.error(`${this.getPeriodLabel(config.periodName)}的结束时间必须大于开始时间`)
          return false
        }
      }

      return true
    },
    dataFormSubmit() {
      this.$refs['dataForm'].validate(async valid => {
        if (valid && this.validatePeriodConfigs()) {
          try {
            const submitData = {
              trainId: this.dataForm.trainId,
              startDate: this.dataForm.dateRange[0],
              endDate: this.dataForm.dateRange[1],
              periodConfigs: this.dataForm.periodConfigs.filter(p => p.enabled)
            }

            const res = await batchConfigTrainSignTime(submitData)

            if (res.code === 200) {
              this.$message.success('批量配置成功')
              this.visible = false
              this.$emit('refreshDataList')
            } else {
              this.$message.error(res.msg || '批量配置失败')
            }
          } catch (error) {
            this.$message.error('批量配置失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.period-config-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.period-config-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  background-color: #fafafa;
}

.period-config-item:last-child {
  margin-bottom: 0;
}

.period-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.period-content {
  margin-top: 10px;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f56c6c;
}
</style>
